package com.sky.sky_server.interceptor;

import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.sky.sky_common.config.JwtProperties;
import com.sky.sky_common.constant.JwtRoleConstant;
import com.sky.sky_common.context.BaseContext;
import com.sky.sky_common.util.JwtService;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor{
    private final JwtService jwtService;
    private final JwtProperties jwtProperties;

    public JwtTokenUserInterceptor(JwtService jwtService, JwtProperties jwtProperties){
        this.jwtService = jwtService;
        this.jwtProperties = jwtProperties;
    }

    public boolean preHandle(@NonNull HttpServletRequest request,@NonNull  HttpServletResponse response,@NonNull  Object handler){
        String auth = request.getHeader(jwtProperties.getUserHeader());
        // 未携带有效token
        if(auth == null || auth.isEmpty()){
            throw new io.jsonwebtoken.JwtException("Missing token");
        }

        // 解析token
        Claims claims = jwtService.parseJwtToken(auth, JwtRoleConstant.USER);
        BaseContext.setCurrentId(Long.parseLong(claims.get("id").toString()));

        // 获取用户id
        return true;
    }

    public void postHandle(@NonNull HttpServletRequest request,@NonNull HttpServletResponse response,@NonNull Object handler,@Nullable ModelAndView modelAndView) throws Exception {
        BaseContext.remove();
   }
}
